package com.wangzh.concurrent.lock.readwritelock;

import java.util.HashMap;
import java.util.Objects;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

//读写锁
public class ReadWriteLockTest {
    public static void main(String[] args) {
        MycacheLock mycache = new MycacheLock();
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() ->{
                mycache.setMap(finalI +"", finalI +"");
            },String.valueOf(i)).start();
        }

        for (int i = 0; i < 5; i++) {
            int finalI = i;
            new Thread(() ->{
                mycache.getKey(finalI +"");
            },String.valueOf(i)).start();
        }
    }
}

class MycacheLock{
    HashMap<String, Object> map = new HashMap<>();

    /**写入锁--独占锁
     * 读锁--共享锁
     * 更加细粒度的锁，和lock对比
     * 写入上锁，和读取同时上锁，可以保证在写入的之后读取
     * 写入上锁，读取没上锁，可能没写入完，就进去读了
     */
    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    public void setMap(String key,Object value){
        readWriteLock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"写入"+key);
            map.put(key, value);
            System.out.println(Thread.currentThread().getName()+"写完毕"+key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.writeLock().unlock();
        }
    }

    public void getKey(String key){
        readWriteLock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName()+"读"+key);
            map.get(key);
            System.out.println(Thread.currentThread().getName()+"读完毕"+key);
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            readWriteLock.readLock().unlock();
        }
    }
//    public void getKey(String key){
//        System.out.println(Thread.currentThread().getName()+"读"+key);
//        map.get(key);
//        System.out.println(Thread.currentThread().getName()+"读完毕"+key);
//    }

}
class Mycache{
    HashMap<String, Object> map = new HashMap<>();

    public void setMap(String key,Object value){
        System.out.println(Thread.currentThread().getName()+"写入"+key);
        map.put(key, value);
        System.out.println(Thread.currentThread().getName()+"写完毕"+key);
    }

    public void getKey(String key){
        System.out.println(Thread.currentThread().getName()+"读"+key);
        map.get(key);
        System.out.println(Thread.currentThread().getName()+"读完毕"+key);
    }

}
